<script setup lang="ts">
  import { ref } from 'vue';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import {
    queryRolesList,
    addRolePermission,
    queryRolePermissionsIds,
    deleteRole,
  } from '@/api/system/role';
  import { useForm } from '@/hooks/arco/useForm';
  import useModeModalHandler from '@/hooks/arco/useModeModalHandler';
  import ListSelect from '@/components/list-select/index.vue';
  import PermissionTree from '@/components/permission-tree/index.vue';
  import { useAutoRequest } from '@/hooks/arco/useAutoLoading';
  import { Message } from '@arco-design/web-vue';

  import Detail from './detail.vue';

  const searchForm = useForm({
    state: {
      roleName: '',
    },
  });
  const skeleton = useSkeleton({
    apiFun: () => queryRolesList(searchForm.state),
  });

  const modalForm = useForm({
    state: {
      permissions: [] as string[],
    },
  });

  const permissionSkeleton = useSkeleton({
    apiFun: queryRolePermissionsIds,
    immediate: false,
    onSuccess(data) {
      modalForm.state.permissions = data;
    },
    isEmpty() {
      return false;
    },
  });

  const editModal = useModeModalHandler({
    onSuccess() {
      skeleton.retry();
    },
  });

  const checkIndex = ref(-1);

  const currentRole = ref();

  const isEdit = ref(false);

  const onItemCheck = (item: any, index: number) => {
    checkIndex.value = index;
    currentRole.value = item;
    permissionSkeleton.execute(item.roleId);
    isEdit.value = false;
  };

  const renderRole = (data: any) => {
    if (!data) {
      return [];
    }
    return [
      {
        label: 'ID',
        value: data.roleId,
      },
      {
        label: '角色名称',
        value: data.roleName,
      },
      {
        label: '使用数量',
        value: data.accountNum,
      },
      {
        label: '创建时间',
        value: data.createdAt,
      },
    ];
  };

  const tabActive = ref(1);

  const [savePermissionLd, savePerReq] = useAutoRequest(addRolePermission, {
    onSuccess() {
      Message.success('保存成功');
      isEdit.value = false;
    },
  });

  const savePer = () => {
    savePerReq({
      roleId: currentRole.value.roleId,
      permissionIds: modalForm.state.permissions.join(','),
    });
  };

  const onBeforeDelete = (): boolean | void | Promise<void | boolean> => {
    return deleteRole(currentRole.value.roleId).then(() => {
      skeleton.retry();
    });
  };
</script>

<template>
  <div class="h-full">
    <Detail v-bind="editModal.bindProps" />
    <!-- <h2 class="text-xl mb-8 font-medium tracking-wide">角色列表</h2> -->
    <div class="flex gap-5 flex-1 h-full">
      <div class="p-0 gap-5 flex flex-col round h-full">
        <a-button
          class="shadow-md h-[40px] text-[16px]"
          type="primary"
          size="large"
          @click="editModal.showAdd()"
        >
          <template #icon>
            <icon-plus />
          </template>
          新建角色
        </a-button>
        <skeleton-view
          v-slot="{ data }"
          class="w-[280px]"
          v-bind="skeleton.bindProps"
        >
          <ListSelect
            :data="data"
            label-prop="roleName"
            @change="onItemCheck"
          />
        </skeleton-view>
      </div>

      <div
        class="flex-1 overflow-y-auto h-full relative py-2 px-4 border rounded shadow"
      >
        <a-empty v-if="checkIndex == -1" class="mt-10"> 请选择角色 </a-empty>
        <a-tabs
          v-else
          v-model:active-key="tabActive"
          size="large"
          class="h-full"
          justify
        >
          <a-tab-pane :key="1">
            <template #title>
              <span class="text-[16px]">角色信息</span>
            </template>
            <div class="p-2">
              <a-descriptions
                class="flex-1"
                :column="1"
                :data="renderRole(currentRole)"
                size="large"
              >
              </a-descriptions>
            </div>
          </a-tab-pane>
          <a-tab-pane :key="2">
            <template #title>
              <span class="text-[16px]">功能权限</span>
            </template>
            <div class="p-2 overflow-y-auto h-full">
              <skeleton-view v-bind="permissionSkeleton.bindProps">
                <a-form v-bind="modalForm.bindProps" layout="vertical">
                  <a-form-item field="permissions" label="权限树" no-style>
                    <PermissionTree
                      v-model:checked-keys="modalForm.state.permissions"
                      :disabled="!isEdit"
                    />
                  </a-form-item>
                </a-form>
              </skeleton-view>
            </div>
          </a-tab-pane>
        </a-tabs>

        <div class="absolute right-12 bottom-5">
          <a-space v-if="tabActive === 1">
            <a-popconfirm type="warning" :on-before-ok="onBeforeDelete">
              <template #content>
                <div class="fle flex-col w-[200px]">
                  <span class="font-semibold"> 确认删除该角色吗？ </span>
                  <span class="text-[13px]" style="color: #333333">
                    提示：角色关联账号的功能权限将一起被删除。
                  </span>
                </div>
              </template>
              <ae-button purpose="delete">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </ae-button>
            </a-popconfirm>

            <ae-button purpose="edit" @click="editModal.showEdit(currentRole)">
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </ae-button>
          </a-space>

          <a-space v-else>
            <ae-button v-if="!isEdit" purpose="edit" @click="isEdit = true">
              编辑
            </ae-button>

            <template v-else>
              <ae-button
                purpose="save"
                :loading="savePermissionLd"
                @click="savePer"
              >
                保存
              </ae-button>
              <ae-button purpose="cancel" @click="isEdit = false">
                取消
              </ae-button>
            </template>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped></style>
